package com.ywk.base.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 链接HTTP形式的接口客户端
 * @author binzec
 */
public class HttpClientUtil {
	
	private final static String CHARSET = "UTF-8";
	
/*=============================================GET============================================================================*/	
	
	/**
	 * GET请求方式
	 * @param url	访问链接
	 */
	public static String get(String url) {
		return sendGet(url, null);
	}
	
	/**
	 * GET请求方式
	 * @param url		访问链接
	 * @param headerMap	设置额外的请求头信息
	 */
	public static String get(String url, Map<String, String> headerMap) {
		return sendGet(url, headerMap);
	}
	
/*=============================================POST============================================================================*/	
	
	/**
	 * POST请求方式
	 * @param url		访问链接
	 * @param param		json格式的参数（如"{\"a1\":\"11\",\"a2\":\"22\"}"）
	 * @param headerMap	设置额外的请求头信息
	 */
	public static String postJson(String url, String param, Map<String, String> headerMap) {
		return sendPost(url, new StringEntity(param, CHARSET), headerMap);
	}
	
	/**
	 * POST请求方式
	 * @param url		访问链接
	 * @param param		json格式的参数（如"{\"a1\":\"11\",\"a2\":\"22\"}"）
	 */
	public static String postJson(String url, String param) {
		return sendPost(url, new StringEntity(param, CHARSET), null);
	}
	
	/**
	 * POST请求方式
	 * @param url		访问链接
	 * @param param(json)	键值对参数
	 * @param headerMap	设置额外的请求头信息
	 */
	public static String post(String url, Map<String, String> param, Map<String, String> headerMap) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (Entry<String, String> e : param.entrySet()) {
			params.add(new BasicNameValuePair(e.getKey(), e.getValue()));
		}
		return sendPost(url, new UrlEncodedFormEntity(params, CHARSET), headerMap);
	}
	
	/**
	 * POST请求方式   返回整个HttpResponse
	 * @param url		访问链接
	 * @param param(json)	键值对参数
	 * @param headerMap	设置额外的请求头信息
	 */
	public static CloseableHttpResponse postRetResp(String url, Map<String, String> param, Map<String, String> headerMap) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (Entry<String, String> e : param.entrySet()) {
			params.add(new BasicNameValuePair(e.getKey(), e.getValue()));
		}
		return sendPostRetResp(url, new UrlEncodedFormEntity(params, CHARSET), headerMap);
	}
	
	
	
	/**
	 * POST请求方式
	 * @param url		访问链接
	 * @param param(json)		键值对参数
	 */
	public static String post(String url, Map<String, String> param) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if(param!=null) {
			for (Entry<String, String> e : param.entrySet()) {
				params.add(new BasicNameValuePair(e.getKey(), e.getValue()));
			}
		}
		
		return sendPost(url, new UrlEncodedFormEntity(params, CHARSET), null);
	}
	
/*=============================================公共方法============================================================================*/	
	
	/**
	 * GET请求方式
	 * @param url		访问链接
	 * @param headerMap	设置额外的请求头信息
	 */
	private static String sendGet(String url, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = getHttpClient();
		try {
			HttpGet httpGet = new HttpGet(url);
			if (headerMap == null) {
				httpGet.addHeader("accept", "application/json");
				httpGet.addHeader("Content-Type", "application/json");
			}
			if (headerMap != null && !headerMap.isEmpty()) {
				for (Entry<String, String> e : headerMap.entrySet()) {
					httpGet.addHeader(e.getKey(), e.getValue());
				}
			}
			CloseableHttpResponse response = httpClient.execute(httpGet);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * POST请求具体逻辑公共方法
	 * @param url		访问链接
	 * @param entity	参数
	 * @param headerMap	设置额外的请求头数据（key-header的name；value-对应name的value）
	 */
	private static String sendPost(String url, HttpEntity entity, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = getHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			if (headerMap == null) {
				httpPost.addHeader("accept", "application/json");
				httpPost.addHeader("Content-Type", "application/json");
			}
			if (headerMap != null && !headerMap.isEmpty()) {
				for (Entry<String, String> e : headerMap.entrySet()) {
					httpPost.addHeader(e.getKey(), e.getValue());
				}
			}
			httpPost.setEntity(entity);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * POST请求具体逻辑方法   返回HttpResponse
	 * @param url		访问链接
	 * @param entity	参数
	 * @param headerMap	设置额外的请求头数据（key-header的name；value-对应name的value）
	 */
	private static CloseableHttpResponse sendPostRetResp(String url, HttpEntity entity, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = getHttpClient();
		try {
			HttpPost httpPost = new HttpPost(url);
			if (headerMap == null) {
				httpPost.addHeader("accept", "application/json");
				httpPost.addHeader("Content-Type", "application/json");
			}
			if (headerMap != null && !headerMap.isEmpty()) {
				for (Entry<String, String> e : headerMap.entrySet()) {
					httpPost.addHeader(e.getKey(), e.getValue());
				}
			}
			httpPost.setEntity(entity);
			return httpClient.execute(httpPost);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				closeHttpClient(httpClient);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 开启httpClient
	 */
	private static CloseableHttpClient getHttpClient() {
		return HttpClients.createDefault();
	}

	/**
	 * 关闭httpClient
	 */
	private static void closeHttpClient(CloseableHttpClient client) throws IOException {
		if (client != null) {
			client.close();
		}
	}

	public static void main(String[] args) {
		/*String resJson = HttpClientUtil.get("http://localhost:3000/getWaterOne");
		Map<String, Object> resMap = JsonUtil.json2Map(resJson, Object.class);
		String s = JSON.toJSONString(resMap);

		Map<String, Object> map = JSON.parseObject(resJson, Map.class);
		RestTemplate restTemplate = new RestTemplate();
		//get请求：getForEntity->获取header+body,getForObject->获取body
		ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:3000/getWaterOne", String.class);
		String responseBody = restTemplate.getForObject("http://localhost:3000/getWaterOne", String.class);
		*/
		RestTemplate restTemplate=new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.set("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
		//封装url参数
		Map<String,String> map = new HashMap();
		String name="汉滨区金州南路85号";
		map.put("ds","{\"keyWord\":\""+name+"\"}");
		map.put("tk","2f56faf6af67860fffaa9f6171fd34f1");

		org.springframework.http.HttpEntity<String> httpEntity = new org.springframework.http.HttpEntity<String>("",headers);
		String url="https://api.tianditu.gov.cn/geocoder?tk={tk}&ds={ds}";
		ResponseEntity<String> responseEntity  = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, map);
		String body = responseEntity.getBody();


		Map<String,Object> response = (Map<String,Object>) JSON.parseObject(body, Map.class);
		Map<String,Object> location = (Map<String,Object>)response.get("location");
		String lon = location.get("lon").toString();
		String lat = location.get("lat").toString();

		System.out.println(body);
	}
	
}
